<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="手动搭建I&#x2F;O网络通信框架2：BIO编程模型实现群聊 转载自https:&#x2F;&#x2F;www.cnblogs.com&#x2F;lbhym&#x2F;p&#x2F;12681787.html  手动搭建I&#x2F;O网络通信框架2：BIO编程模型实现群聊在第一章中运用Socket和ServerSocket简单的实现了网络通信。这一章，利用BIO编程模型进行升级改造，实现群聊聊天室。 所谓BIO，就是Block IO，阻塞式的IO。这个阻塞主要发">
<meta property="og:type" content="article">
<meta property="og:title" content="手动搭建I&#x2F;O网络通信框架2：BIO编程模型实现群聊">
<meta property="og:url" content="http://littlefxc.github.io/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B62%EF%BC%9ABIO%E7%BC%96%E7%A8%8B%E6%A8%A1%E5%9E%8B%E5%AE%9E%E7%8E%B0%E7%BE%A4%E8%81%8A/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="手动搭建I&#x2F;O网络通信框架2：BIO编程模型实现群聊 转载自https:&#x2F;&#x2F;www.cnblogs.com&#x2F;lbhym&#x2F;p&#x2F;12681787.html  手动搭建I&#x2F;O网络通信框架2：BIO编程模型实现群聊在第一章中运用Socket和ServerSocket简单的实现了网络通信。这一章，利用BIO编程模型进行升级改造，实现群聊聊天室。 所谓BIO，就是Block IO，阻塞式的IO。这个阻塞主要发">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411190359629-713089288.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193234531-59946096.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193327017-1431424368.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193358577-1779741867.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193747903-851197924.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193923381-1365643546.png">
<meta property="article:published_time" content="2021-05-28T11:39:32.000Z">
<meta property="article:modified_time" content="2021-10-19T02:14:54.749Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="netty">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411190359629-713089288.png">


<link rel="canonical" href="http://littlefxc.github.io/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B62%EF%BC%9ABIO%E7%BC%96%E7%A8%8B%E6%A8%A1%E5%9E%8B%E5%AE%9E%E7%8E%B0%E7%BE%A4%E8%81%8A/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>手动搭建I/O网络通信框架2：BIO编程模型实现群聊 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI-O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B62%EF%BC%9ABIO%E7%BC%96%E7%A8%8B%E6%A8%A1%E5%9E%8B%E5%AE%9E%E7%8E%B0%E7%BE%A4%E8%81%8A"><span class="nav-text">手动搭建I&#x2F;O网络通信框架2：BIO编程模型实现群聊</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI-O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B62%EF%BC%9ABIO%E7%BC%96%E7%A8%8B%E6%A8%A1%E5%9E%8B%E5%AE%9E%E7%8E%B0%E7%BE%A4%E8%81%8A-1"><span class="nav-text">手动搭建I&#x2F;O网络通信框架2：BIO编程模型实现群聊</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF%EF%BC%9A"><span class="nav-text">服务器端：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF%EF%BC%9A"><span class="nav-text">客户端：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%90%E8%A1%8C%E6%B5%8B%E8%AF%95%EF%BC%9A"><span class="nav-text">运行测试：</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B62%EF%BC%9ABIO%E7%BC%96%E7%A8%8B%E6%A8%A1%E5%9E%8B%E5%AE%9E%E7%8E%B0%E7%BE%A4%E8%81%8A/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          手动搭建I/O网络通信框架2：BIO编程模型实现群聊
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-05-28 19:39:32" itemprop="dateCreated datePublished" datetime="2021-05-28T19:39:32+08:00">2021-05-28</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-10-19 10:14:54" itemprop="dateModified" datetime="2021-10-19T10:14:54+08:00">2021-10-19</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Netty/" itemprop="url" rel="index"><span itemprop="name">Netty</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="手动搭建I-O网络通信框架2：BIO编程模型实现群聊"><a href="#手动搭建I-O网络通信框架2：BIO编程模型实现群聊" class="headerlink" title="手动搭建I/O网络通信框架2：BIO编程模型实现群聊"></a>手动搭建I/O网络通信框架2：BIO编程模型实现群聊</h1><blockquote>
<p>转载自<a target="_blank" rel="noopener" href="https://www.cnblogs.com/lbhym/p/12681787.html">https://www.cnblogs.com/lbhym/p/12681787.html</a></p>
</blockquote>
<h1 id="手动搭建I-O网络通信框架2：BIO编程模型实现群聊-1"><a href="#手动搭建I-O网络通信框架2：BIO编程模型实现群聊-1" class="headerlink" title="手动搭建I/O网络通信框架2：BIO编程模型实现群聊"></a><strong>手动搭建I/O网络通信框架2：BIO编程模型实现群聊</strong></h1><p>在第一章中运用Socket和ServerSocket简单的实现了网络通信。这一章，利用BIO编程模型进行升级改造，实现群聊聊天室。</p>
<p>所谓BIO，就是Block IO，阻塞式的IO。这个阻塞主要发生在：ServerSocket接收请求时（accept()方法）、InputStream、OutputStream（输入输出流的读和写）都是阻塞的。这个可以在下面代码的调试中发现，比如在客户端接收服务器消息的输入流处打上断点，除非服务器发来消息，不然断点是一直停在这个地方的。也就是说这个线程在这时间是被阻塞的。</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411190359629-713089288.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200411190359629-713089288.png"></p>
<p>如图：当一个客户端请求进来时，接收器会为这个客户端分配一个工作线程，这个工作线程专职处理客户端的操作。在上一章中，服务器接收到客户端请求后就跑去专门服务这个客户端了，所以当其他请求进来时，是处理不到的。</p>
<p>看到这个图，很容易就会想到线程池，BIO是一个相对简单的模型，实现它的关键之处也在于线程池。</p>
<p>在上代码之前，先大概说清楚每个类的作用，以免弄混淆。更详细的说明，都写在注释当中。</p>
<h2 id="服务器端："><a href="#服务器端：" class="headerlink" title="服务器端："></a><strong>服务器端：</strong></h2><p>ChatServer:这个类的作用就像图中的Acceptor。它有两个比较关键的全局变量，一个就是存储在线用户信息的Map，一个就是线程池。这个类会监听端口，接收客户端的请求，然后为客户端分配工作线程。还会提供一些常用的工具方法给每个工作线程调用，比如：发送消息、添加在线用户等。我之前简单用过Netty和WebSocket，这个类看上去就已经和这些框架有点相似了。学习IO编程模型也是为了接下来深入学习Netty做准备。</p>
<p>ChatHandler:这个类就是工作线程的类。在这个项目中，它的工作很简单：把接收到的消息转发给其他客户端，当然还有一些小功能，比如添加\移除在线用户。</p>
<h2 id="客户端："><a href="#客户端：" class="headerlink" title="客户端："></a><strong>客户端：</strong></h2><p>相较于服务器，客户端的改动较小，主要是把等待用户输入信息这个功能分到其他线程做，不然这个功能会一直阻塞主线程，导致无法接收其他客户端的消息。</p>
<p>ChatClient:客户端启动类，也就是主线程，会通过Socket和服务器连接。也提供了两个工具方法：发送消息和接收消息。</p>
<p>UserInputHandler:专门负责等待用户输入信息的线程，一旦有信息键入，就马上发送给服务器。</p>
<p>首先创建两个包区分一下客户端和服务器，client和server</p>
<p><strong>服务器端ChatServer：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ChatServer</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> DEFAULT_PORT = <span class="number">8888</span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 创建一个Map存储在线用户的信息。这个map可以统计在线用户、针对这些用户可以转发其他用户发送的消息</span></span><br><span class="line"><span class="comment">     * 因为会有多个线程操作这个map，所以为了安全起见用ConcurrentHashMap</span></span><br><span class="line"><span class="comment">     * 在这里key就是客户端的端口号，但在实际中肯定不会用端口号区分用户，如果是web的话一般用session。</span></span><br><span class="line"><span class="comment">     * value是IO的Writer，用以存储客户端发送的消息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> Map&lt;Integer, Writer&gt; map=<span class="keyword">new</span> ConcurrentHashMap&lt;&gt;();</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 创建线程池，线程上限为10个，如果第11个客户端请求进来，服务器会接收但是不会去分配线程处理它。</span></span><br><span class="line"><span class="comment">     * 前10个客户端的聊天记录，它看不见。当有一个客户端下线时，这第11个客户端就会被分配线程，服务器显示在线</span></span><br><span class="line"><span class="comment">     * 大家可以把10再设置小一点，测试看看</span></span><br><span class="line"><span class="comment">     * */</span></span><br><span class="line">    <span class="keyword">private</span> ExecutorService executorService= Executors.newFixedThreadPool(<span class="number">10</span>);</span><br><span class="line">    <span class="comment">//客户端连接时往map添加客户端</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addClient</span><span class="params">(Socket socket)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (socket != <span class="keyword">null</span>) &#123;</span><br><span class="line">            BufferedWriter writer = <span class="keyword">new</span> BufferedWriter(</span><br><span class="line">                    <span class="keyword">new</span> OutputStreamWriter(socket.getOutputStream())</span><br><span class="line">            );</span><br><span class="line">            map.put(socket.getPort(), writer);</span><br><span class="line">            System.out.println(<span class="string">&quot;Client[&quot;</span>+socket.getPort()+<span class="string">&quot;]:Online&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//断开连接时map里移除客户端</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">removeClient</span><span class="params">(Socket socket)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (socket != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (map.containsKey(socket.getPort())) &#123;</span><br><span class="line">                map.get(socket.getPort()).close();</span><br><span class="line">                map.remove(socket.getPort());</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;Client[&quot;</span> + socket.getPort() + <span class="string">&quot;]Offline&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//转发客户端消息，这个方法就是把消息发送给在线的其他的所有客户端</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sendMessage</span><span class="params">(Socket socket, String msg)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//遍历在线客户端</span></span><br><span class="line">        <span class="keyword">for</span> (Integer port : map.keySet()) &#123;</span><br><span class="line">            <span class="comment">//发送给在线的其他客户端</span></span><br><span class="line">            <span class="keyword">if</span> (port != socket.getPort()) &#123;</span><br><span class="line">                Writer writer = map.get(port);</span><br><span class="line">                writer.write(msg);</span><br><span class="line">                writer.flush();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//接收客户端请求，并分配Handler去处理请求</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> (ServerSocket serverSocket = <span class="keyword">new</span> ServerSocket(DEFAULT_PORT)) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;Server Start,The Port is:&quot;</span>+DEFAULT_PORT);</span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">true</span>)&#123;</span><br><span class="line">                <span class="comment">//等待客户端连接</span></span><br><span class="line">                Socket socket=serverSocket.accept();</span><br><span class="line">                <span class="comment">//为客户端分配一个ChatHandler线程</span></span><br><span class="line">                executorService.execute(<span class="keyword">new</span> ChatHandler(<span class="keyword">this</span>,socket));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ChatServer server=<span class="keyword">new</span> ChatServer();</span><br><span class="line">        server.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>服务器端ChatHandler：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ChatHandler</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> ChatServer server;</span><br><span class="line">    <span class="keyword">private</span> Socket socket;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//构造函数，ChatServer通过这个分配Handler线程</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ChatHandler</span><span class="params">(ChatServer server, Socket socket)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.server = server;</span><br><span class="line">        <span class="keyword">this</span>.socket = socket;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//往map里添加这个客户端</span></span><br><span class="line">            server.addClient(socket);</span><br><span class="line">            <span class="comment">//读取这个客户端发送的消息</span></span><br><span class="line">            BufferedReader reader = <span class="keyword">new</span> BufferedReader(</span><br><span class="line">                    <span class="keyword">new</span> InputStreamReader(socket.getInputStream())</span><br><span class="line">            );</span><br><span class="line">            String msg = <span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">while</span> ((msg = reader.readLine()) != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//这样拼接是为了让其他客户端也能看清是谁发送的消息</span></span><br><span class="line">                String sendmsg = <span class="string">&quot;Client[&quot;</span> + socket.getPort() + <span class="string">&quot;]:&quot;</span> + msg;</span><br><span class="line">                <span class="comment">//服务器打印这个消息</span></span><br><span class="line">                System.out.println(sendmsg);</span><br><span class="line">                <span class="comment">//将收到的消息转发给其他在线客户端</span></span><br><span class="line">                server.sendMessage(socket, sendmsg + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">                <span class="keyword">if</span> (msg.equals(<span class="string">&quot;quit&quot;</span>)) &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">//如果用户退出或者发生异常，就在map中移除该客户端</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                server.removeClient(socket);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>客户端ChatClient:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ChatClient</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> BufferedReader reader;</span><br><span class="line">    <span class="keyword">private</span> BufferedWriter writer;</span><br><span class="line">    <span class="keyword">private</span> Socket socket;</span><br><span class="line">    <span class="comment">//发送消息给服务器</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sendToServer</span><span class="params">(String msg)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//发送之前，判断socket的输出流是否关闭</span></span><br><span class="line">        <span class="keyword">if</span> (!socket.isOutputShutdown()) &#123;</span><br><span class="line">            <span class="comment">//如果没有关闭就把用户键入的消息放到writer里面</span></span><br><span class="line">            writer.write(msg + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">            writer.flush();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//从服务器接收消息</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">receive</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        String msg = <span class="keyword">null</span>;</span><br><span class="line">        <span class="comment">//判断socket的输入流是否关闭</span></span><br><span class="line">        <span class="keyword">if</span> (!socket.isInputShutdown()) &#123;</span><br><span class="line">            <span class="comment">//没有关闭的话就可以通过reader读取服务器发送来的消息。注意：如果没有读取到消息线程会阻塞在这里</span></span><br><span class="line">            msg = reader.readLine();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> msg;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//和服务创建连接</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            socket = <span class="keyword">new</span> Socket(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8888</span>);</span><br><span class="line">            reader=<span class="keyword">new</span> BufferedReader(</span><br><span class="line">                    <span class="keyword">new</span> InputStreamReader(socket.getInputStream())</span><br><span class="line">            );</span><br><span class="line">            writer=<span class="keyword">new</span> BufferedWriter(</span><br><span class="line">                    <span class="keyword">new</span> OutputStreamWriter(socket.getOutputStream())</span><br><span class="line">            );</span><br><span class="line">            <span class="comment">//新建一个线程去监听用户输入的消息</span></span><br><span class="line">            <span class="keyword">new</span> Thread(<span class="keyword">new</span> UserInputHandler(<span class="keyword">this</span>)).start();</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 不停的读取服务器转发的其他客户端的信息</span></span><br><span class="line"><span class="comment">             * 记录一下之前踩过的小坑：</span></span><br><span class="line"><span class="comment">             * 这里一定要创建一个msg接收信息，如果直接用receive()方法判断和输出receive()的话会造成有的消息不会显示</span></span><br><span class="line"><span class="comment">             * 因为receive()获取时，在返回之前是阻塞的，一旦接收到消息才会返回，也就是while这里是阻塞的，一旦有消息就会进入到while里面</span></span><br><span class="line"><span class="comment">             * 这时候如果输出的是receive(),那么上次获取的信息就会丢失，然后阻塞在System.out.println</span></span><br><span class="line"><span class="comment">             * */</span></span><br><span class="line">            String msg=<span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">while</span> ((msg=receive())!=<span class="keyword">null</span>)&#123;</span><br><span class="line">                System.out.println(msg);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">               <span class="keyword">if</span>(writer!=<span class="keyword">null</span>)&#123;</span><br><span class="line">                   writer.close();</span><br><span class="line">               &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> ChatClient().start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>　<strong>客户端UserInputHandler:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserInputHandler</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> ChatClient client;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UserInputHandler</span><span class="params">(ChatClient client)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.client = client;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//接收用户输入的消息</span></span><br><span class="line">            BufferedReader reader = <span class="keyword">new</span> BufferedReader(</span><br><span class="line">                    <span class="keyword">new</span> InputStreamReader(System.in)</span><br><span class="line">            );</span><br><span class="line">            <span class="comment">//不停的获取reader中的System.in，实现了等待用户输入的效果</span></span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">                String input = reader.readLine();</span><br><span class="line">                <span class="comment">//向服务器发送消息</span></span><br><span class="line">                client.sendToServer(input);</span><br><span class="line">                <span class="keyword">if</span> (input.equals(<span class="string">&quot;quit&quot;</span>))</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="运行测试："><a href="#运行测试：" class="headerlink" title="运行测试："></a><strong>运行测试：</strong></h2><p>通过打开终端，通过javac编译。如果大家是在IDEA上编码的话可能会报编码错误，在javac后面加上-encoding utf-8再接java文件就好了。</p>
<p>编译后运行，通过java运行时，又遇到了一个坑。会报找不到主类的错误，原来是因为加上两个包，要在class文件名前面加上包名。比如当前在src目录，下面有client和server两个包，要这么运行：java client.XXXX。可我之前明明在client文件夹下运行的java，也是不行，不知道为什么。</p>
<p>接着测试：</p>
<p>1.首先在一个终端里运行ChatServer，打开服务器</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193234531-59946096.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200411193234531-59946096.png"></p>
<p>2.在第二个终端里打开ChatClient，暂且叫A，此时服务器的终端显示：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193327017-1431424368.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200411193327017-1431424368.png"></p>
<p>3.类似的，在第三个终端里打开ChatClient，暂且叫B，此时服务器显示：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193358577-1779741867.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200411193358577-1779741867.png"></p>
<p>4.A中输入hi,除了服务器会打印hi外，B中也会显示，图片中的端口号和前面的不一样，是因为中间出了点小问题，前三张截图和后面的不是同时运行的。实际中同一个客户端会显示一样的端口号：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193747903-851197924.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200411193747903-851197924.png"></p>
<p>5.当客户端输入quit时就会断开连接，最后，服务器的显示为：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200411193923381-1365643546.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200411193923381-1365643546.png"></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/netty/" rel="tag"># netty</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B63%EF%BC%9ANIO%E7%BC%96%E7%A8%8B%E6%A8%A1%E5%9E%8B%EF%BC%8C%E5%8D%87%E7%BA%A7%E6%94%B9%E9%80%A0%E8%81%8A%E5%A4%A9%E5%AE%A4/" rel="prev" title="手动搭建I/O网络通信框架3：NIO编程模型，升级改造聊天室">
                  <i class="fa fa-chevron-left"></i> 手动搭建I/O网络通信框架3：NIO编程模型，升级改造聊天室
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B61%EF%BC%9ASocket%E5%92%8CServerSocket%E5%85%A5%E9%97%A8%E5%AE%9E%E6%88%98%EF%BC%8C%E5%AE%9E%E7%8E%B0%E5%8D%95%E8%81%8A/" rel="next" title="手动搭建I/O网络通信框架1：Socket和ServerSocket入门实战，实现单聊">
                  手动搭建I/O网络通信框架1：Socket和ServerSocket入门实战，实现单聊 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
